import {
  Form,
  Input,
  InputNumber,
  Select,
  TimePicker,
  Checkbox,
  Button,
  Space,
  Switch,
  Radio
} from "antd";
import React from "react";
import TheUpload from "@/components/TheUpload";
import TheTable from "@/components/TheTable";
import TheQuill from "@/components/TheQuill";
import { apiServiceClassifyGetList, apiStoreServiceLabelList, apiStoreServiceEdit, apiStoreServiceUpdateState, apiServiceDetail } from '@/request/services'
import { getDateTime4 } from '@/utils/getDate'
import Coupon from './coupon';
import TheDialog from '@/components/TheDialog';
import TheButton from "@/components/TheButton";
import _ from 'lodash'

const { RangePicker } = TimePicker;

class Edit extends React.Component {
  constructor() {
    super()
    this.couponRef = React.createRef()
    this.couponTableRef = React.createRef()
    this.state = {
      tags: [],
      tagsValue: [],
      options: [],
      giftBalanceShow: false,
      radiovalue: 0,
      columns: [
        {
          title: "优惠券ID",
          dataIndex: "couponId",
          key: "couponId",
        },
        {
          title: "优惠券名称",
          dataIndex: "couponTitle",
          key: "couponTitle",
        },
        {
          title: "范围",
          dataIndex: "commodityScope",
          key: "commodityScope",
          render: (text, render) => {
            let label = ''
            switch (text) {
              case 0:
                label = "全部商品可用"
                break;
              case 1:
                label = "限制品类可用"
                break;
              case 2:
                label = "商品券"
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "优惠",
          dataIndex: "couponPrice",
          key: "couponPrice",
          render: (text, render) => {
            let label = ''
            switch (render.usePrice) {
              case -1:
                label = '无门槛，'
                break;
              default:
                label = "满" + (render.usePrice) / 100 + "可用，"
            }
            switch (render.couponType) {
              case 'J':
                label += "减免" + text / 100 + "元"
                break;
              case 'Z':
                label += "打" + text / 10 + "折"
                if (render.couponMaxPrice !== -1) {
                  label += '，最大折扣金额' + (render.couponMaxPrice) / 100 + '元'
                }
                break;
              default:
                label = "字段值错误"
            }
            return label
          }
        },
        {
          title: "发放数量（张）",
          dataIndex: "giftCount",
          key: "giftCount",
          render: (text, record, index) => {
            return <InputNumber value={text} min={1} max={100} precision={0} onChange={(value) => this.gitfCountChange(value, index)} />
          }
        },
        {
          title: "操作",
          fixed: "right",
          render: (text, render, index) => {
            return (
              <div>
                <TheButton onClick={(render) => this.couponDel(render, index)}>删除</TheButton>
              </div>
            );
          },
        },
      ],
      visible: false,
      switchDateSelect: true,
      dataSource: []
    };
  }
  async componentDidMount() {
    await this.getClassifyList()
    await this.getLabelList()
    await this.getData()
  }
  getData = async () => {
    const { serviceId } = this.props
    let res = await apiServiceDetail({ serviceId })
    if (res.code === 0 && res.data) {
      let data = res.data
      let formData = {
        serviceClassifyId: data.serviceClassifyId,
        serviceName: data.serviceName,
        serviceShowFile: data.serviceShowFile,
        serviceBannerFile: data.serviceBannerFile,
        petType: data.petType,
        switchDateSelect: { Y: true, N: false }[data.switchDateSelect],
        petWeightStart: data.petWeightStart,
        petWeightEnd: data.petWeightEnd,
        serviceRealPrice: React.$transNum(data.serviceRealPrice, 2, -2),
        time: [React.$moment(data.serviceStartTime, 'HH:mm'), React.$moment(data.serviceEndTime, 'HH:mm')],
        serviceShowLabelIds: data.serviceShowLabelIds,
        serviceTxt: data.serviceTxt,
        giftBalance: React.$transNum(data.giftBalance, 2, -2)
      }
      if (data.petType !== null) {
        this.setState({
          radiovalue: data.petType
        })
      } else {
        this.setState({
          radiovalue: 2
        })
      }
      let fileList = [{
        name: 'image',
        uid: -1,
        status: 'done',
        url: data.serviceShowFile
      }]
      let bannerList = _.toString(data.serviceBannerFile).split(',').map((v, i) => {
        return {
          name: 'image',
          uid: i + 1,
          url: v,
          status: 'done'
        }
      })
      let tagsValue = _.toString(data.serviceShowLabelIds).split(',')
      this.tagsChange(tagsValue)
      let serviceTxt = data.serviceTxt
      let storeId = data.storeId
      // 判断当前类型是否会员卡
      let arr = this.state.options.filter(item => item.value === data.serviceClassifyId)
      this.setState({
        giftBalanceShow: arr.length > 0 && arr[0].label.indexOf('会员卡') > -1 ? true : false,
        fileList,
        serviceTxt,
        storeId,
        switchDateSelect: { Y: true, N: false }[data.switchDateSelect],
        bannerList,
        dataSource: data.storeServiceCouponVos ? data.storeServiceCouponVos : []
      }, () => {
        this.formRef.setFieldsValue({ ...formData })
      })
    }
  }
  getClassifyList = async () => {
    let res = await apiServiceClassifyGetList()
    if (res.data && res.code === 0) {
      let options = res.data.map(v => {
        return {
          label: v.serviceClassifyName,
          value: v.serviceClassifyId
        }
      })
      this.setState({ options })
    }
  }
  getLabelList = async () => {
    let res = await apiStoreServiceLabelList()
    if (res.data && res.code === 0) {
      let tags = res.data.map(v => {
        return {
          label: v.serviceShowLabelName,
          value: v.serviceShowLabelId
        }
      })
      this.setState({ tags })
    }
  }
  tagsChange = (value) => {
    this.setState({ tagsValue: value }, () => {
      this.formRef.setFieldsValue({
        serviceShowLabelIds: value.join(',')
      })
      let { tags, tagsValue } = this.state;
      if (tagsValue.length === 5) {
        this.setState({
          tags: tags.map((v) => {
            return {
              ...v,
              disabled: !tagsValue.includes(v.value),
            };
          }),
        });
      } else {
        this.setState({
          tags: tags.map((v) => {
            return {
              ...v,
              disabled: false,
            };
          }),
        });
      }
    });
  };
  getFileResult = (file) => {
    let serviceShowFile = ''
    if (file && file.length) {
      serviceShowFile = file.map(v => {
        if (v.response && v.response.data && v.response.code === 0) {
          return v.response.data
        } else {
          return ''
        }
      }).join(',')
    } else {
      serviceShowFile = ''
    }
    this.formRef.setFieldsValue({ serviceShowFile })
  }
  getFileBannerResult = (value) => {
    if (value.length) {
      let str = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else {
          return v.url
        }
      }).join(',')
      this.formRef.setFieldsValue({ serviceBannerFile: str });
    } else {
      this.formRef.setFieldsValue({ serviceBannerFile: '' });
    }
    // let serviceBannerFile = ''
    // if (file && file.length) {
    //   serviceBannerFile = file.map(v => {
    //     if (v.response && v.response.data && v.response.code === 0) {
    //       return v.response.data
    //     } else {
    //       return ''
    //     }
    //   }).join(',')
    // } else {
    //   serviceBannerFile = ''
    // }
    // this.formRef.setFieldsValue({ serviceBannerFile })
  }
  setNewsContent = (value) => {
    this.formRef.setFieldsValue({ serviceTxt: value })
  };
  onFinish = async value => {
    this.setState({ btnLoading: true })
    const { giftBalanceShow } = this.state
    if (value.time) {
      value.serviceStartTime = getDateTime4(value.time[0])
      value.serviceEndTime = getDateTime4(value.time[1])
    }
    if (value.petWeightStart === null) {
      value.petWeightStart = 0
    }
    if (value.petWeightEnd === null) {
      value.petWeightEnd = 0
    }
    if (value.switchDateSelect == undefined) {
      value.switchDateSelect = 'Y'
    } else {
      value.switchDateSelect = value.switchDateSelect ? 'Y' : 'N'
    }
    delete (value.time)
    value.petType = this.state.radiovalue
    value.giveCoupon = giftBalanceShow ? 1 : 0
    value.storeServiceCoupons = this.state.dataSource
    value.serviceRealPrice = React.$transNum(value.serviceRealPrice, 0, 2)
    if (value.giftBalance) {
      value.giftBalance = React.$transNum(value.giftBalance, 0, 2)

    }
    let res = await apiStoreServiceEdit({ ...value, serviceId: this.props.serviceId, storeId: this.state.storeId })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.setState({ btnLoading: false })
      this.props.closeDialog()
      this.props.reload()
    }
  }
  handleChange(value, that) {
    let flag = that.state.options.filter(item => item.value === value)
    if (flag.length > 0 && flag[0].label.indexOf('会员卡') > -1) {
      this.setState({
        giftBalanceShow: true
      })
    } else {
      this.setState({
        giftBalanceShow: false
      })
    }
  }
  onSave = async () => {
    this.setState({ btnLoading: true })
    const { giftBalanceShow } = this.state
    await this.formRef.validateFields().then(async response => {
      let value = this.formRef.getFieldsValue()
      if (value.time) {
        value.serviceStartTime = getDateTime4(value.time[0])
        value.serviceEndTime = getDateTime4(value.time[1])
      }
      if (value.petWeightStart === null) {
        value.petWeightStart = 0
      }
      if (value.petWeightEnd === null) {
        value.petWeightEnd = 0
      }
      delete (value.time)
      if (value.switchDateSelect == undefined) {
        value.switchDateSelect = 'Y'
      } else {
        value.switchDateSelect = value.switchDateSelect ? 'Y' : 'N'
      }
      value.serviceRealPrice = React.$transNum(value.serviceRealPrice, 0, 2)
      if (value.giftBalance) {
        value.giftBalance = React.$transNum(value.giftBalance, 0, 2)
      }
      value.petType = this.state.radiovalue
      value.giveCoupon = giftBalanceShow ? 1 : 0
      value.storeServiceCoupons = this.state.dataSource
      let res = await apiStoreServiceEdit({ ...value, serviceId: this.props.serviceId, storeId: this.state.storeId })
      if (res.code === 0 && res.data) {
        let response = await apiStoreServiceUpdateState({ serviceId: this.props.serviceId, reviewStatus: 'S' })
        if (response.code === 0) {
          React.$message({
            type: 'info',
            content: '发布成功'
          })
          this.setState({ btnLoading: false })
          this.props.closeDialog()
          this.props.reload()
        } else {
          this.setState({ btnLoading: false })
        }
      } else {
        this.setState({ btnLoading: false })
      }
    }).catch(err => {
      this.setState({ btnLoading: false })
    })
  }
  radioChange = (e) => {
    this.setState({
      radiovalue: e.target.value,
    }, () => {

    })
  }

  couponChange = () => {
    this.setState({
      visible: true
    })
  }
  detailClose = () => {
    this.setState({ visible: false, });
  };

  locationSave = () => {
    const { dataSource } = this.state
    let data = this.couponRef.state.selectedKeys
    console.log(data, "data");
    let array = []
    Object.keys(data).forEach((v) => {
      if (data[v]) {
        Object.keys(data[v]).forEach((i) => {
          data[v][i].map(res => {
            let row = {
              couponId: res.couponId,
              couponTitle: res.couponTitle,
              commodityScope: res.commodityScope,
              couponPrice: res.couponPrice,
              usePrice: res.usePrice,
              couponType: res.couponType,
              couponMaxPrice: res.couponMaxPrice,
              giftCount: "1",
            }
            array.push(row)
          })
        })
      }
    })
    console.log(_.isEmpty(array));
    let newdataSource = _.isEmpty(array) ? dataSource : dataSource.concat(array)
    let newJson = []
    for (const item1 of newdataSource) {  //循环json数组对象的内容
      let flag = true;  //建立标记，判断数据是否重复，true为不重复
      for (const item2 of newJson) {  //循环新数组的内容
        if (item1.couponId === item2.couponId) { //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
          flag = false;
        }
      }
      if (flag) { //判断是否重复
        newJson.push(item1); //不重复的放入新数组。  新数组的内容会继续进行上边的循环。
      }
    }
    this.setState({
      dataSource: newJson
    }, () => {
      this.detailClose()
    })
  }
  couponDel = (row, index) => {
    const { dataSource } = this.state
    let data = JSON.parse(JSON.stringify(dataSource))
    data.splice(index, 1)
    this.setState({
      dataSource: data
    })
  }

  gitfCountChange = (e, v) => {
    const { dataSource } = this.state
    let data = JSON.parse(JSON.stringify(dataSource))
    data[v].giftCount = e
    this.setState({
      dataSource: data
    })
  }
  setDataSwitch = (e) => {
    console.log('e:', e);
    this.setState({
      switchDateSelect: e
    })
  }
  render() {
    const { tags, tagsValue, dataSource, options, visible, fileList, serviceTxt, bannerList, btnLoading, switchDateSelect, giftBalanceShow, radiovalue, columns } = this.state;
    return (
      <>
        <Form ref={ref => this.formRef = ref} onFinish={this.onFinish}>
          <div style={{ fontSize: 16, fontWeight: "bold", marginBottom: 20 }}>
            基础信息
          </div>
          <Form.Item label="服务类型" name={"serviceClassifyId"} rules={[{ required: true }]}>
            <Select allowClear options={options} placeholder="请选择服务类型" onChange={(value) => this.handleChange(value, this)} />
          </Form.Item>
          <Form.Item label="服务名称" name={"serviceName"} rules={[{ required: true }]}>
            <Input maxLength={60} placeholder="请输入服务名称" />
          </Form.Item>
          <Form.Item label="服务logo" name={"serviceShowFile"} rules={[{ required: true }]}>
            {fileList && <TheUpload fileList={fileList} getFileResult={this.getFileResult} len={1} />}
          </Form.Item>
          <Form.Item label="服务图片" name={"serviceBannerFile"} rules={[{ required: true }]}>
            { <TheUpload fileList={bannerList} getFileResult={this.getFileBannerResult} len={10} />}
          </Form.Item>
          <Form.Item label="宠物种类" name={"petType"} >
            <Radio.Group defaultValue={radiovalue} onChange={this.radioChange} >
              <Radio onChange={this.radioChange} value={0} >狗</Radio>
              <Radio onChange={this.radioChange} value={1} >猫</Radio>
              <Radio onChange={this.radioChange} value={3} >异宠</Radio>
              <Radio onChange={this.radioChange} value={2} >不限制</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="宠物重量(kg)" name={"petWeightStart"}
            style={{ width: 200, float: "left" }} >
            <InputNumber
              label="最小"
              style={{
                width: 100,
                textAlign: 'center',
              }}
              min={0}
              max={999}
              precision={2}
              defaultValue={0}
            />
          </Form.Item>
          <div style={{ float: "left" }} >~</div>
          <Form.Item name={"petWeightEnd"} >
            <InputNumber
              label="最大"
              className="site-input-right"
              style={{
                width: 100,
                textAlign: 'center',
                float: 'left'
              }}
              min={0}
              max={999}
              precision={2}
              defaultValue={0}
            />

          </Form.Item>

          <Form.Item label="服务价格" name={"serviceRealPrice"} rules={[{ required: true }]}>
            <InputNumber min={0.01} precision={2} placeholder="请输入服务价格" />
          </Form.Item>
          {
            giftBalanceShow ? (<Form.Item label="赠送余额" name={"giftBalance"} rules={[{ required: true }]}>
              <InputNumber placeholder="请输入赠送余额" />
            </Form.Item>) : null
          }
          {
            giftBalanceShow ? (<Form.Item label="赠送卡券" >
              <Button onClick={this.couponChange} >选择优惠券</Button>
              <div style={{ height: "10px" }}></div>
              <Form.Item name="storeServiceCoupons">
                <TheTable columns={columns} dataSource={dataSource} ref={ref => this.couponTableRef = ref} />
              </Form.Item>
            </Form.Item>) : null
          }
          <Form.Item label="预约时间" name={"time"} rules={[{ required: true }]}>
            <RangePicker format="HH:mm" />
          </Form.Item>
          <Form.Item label="服务标签" name={"serviceShowLabelIds"} rules={[{ required: true }]}>
            <Checkbox.Group value={tagsValue} options={tags} onChange={this.tagsChange} />
            {`${tagsValue.length}/5`}
          </Form.Item>
          {this.props.businessCategory == "3" && <Form.Item label="日期选择" name="switchDateSelect" >
            <Switch checked={switchDateSelect} onChange={this.setDataSwitch} />
          </Form.Item>}
          <div
            style={{
              fontSize: 16,
              fontWeight: "bold",
              marginBottom: 20,
              paddingTop: 20,
              borderTop: "1px solid #f2f2f2",
            }}
          >
            服务说明
          </div>
          <Form.Item name={"serviceTxt"} rules={[{ required: true, message: '请输入服务说明' }]}>
            {serviceTxt && <TheQuill defaultValue={serviceTxt} setNewsContent={this.setNewsContent} />}
          </Form.Item>
          <Form.Item>
            <div style={{ display: "flex", justifyContent: "center" }}>
              <Space>
                <Button onClick={this.props.closeDialog}>取消</Button>
                <Button htmlType="submit" loading={btnLoading}>保存</Button>
                <Button type="primary" onClick={this.onSave} loading={btnLoading}>
                  发布
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
        <TheDialog title="优惠券" visible={visible} handleCancel={this.detailClose} handleOk={this.locationSave} >
          <Coupon ref={ref => this.couponRef = ref} />
        </TheDialog>
      </>
    );
  }
}

export default Edit;
